package Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter{
    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpSession session = req.getSession(true);
        Object user = session.getAttribute("user");
        String uri = req.getRequestURI();
        if( uri.contains("/homepage.jsp") || uri.contains("/login/dgut") || uri.contains("/LogoutServlet")) {
            chain.doFilter(req, resp);
        }
        else{
            if(user == null)
                resp.sendRedirect("/homepage.jsp");
            else
                chain.doFilter(req, resp);
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }
}
